#include "configmanager.h"
#include "app_version.h"
#include "securetokenmanager.h"

// 静态成员变量定义
QJsonObject ConfigManager::s_config;
QString ConfigManager::s_configPath;
bool ConfigManager::s_loaded = false;

QString ConfigManager::getCurrentVersion()
{
    // 使用统一的版本管理系统
    return LimeReader::AppVersion::getAppVersion();
}


void ConfigManager::setUserToken(const QString& token)
{

    // 使用安全Token管理器存储
    SecureTokenManager& secureManager = SecureTokenManager::instance();
    QString userEmail = getUserEmail();
    QString hash = secureManager.encryptAndStoreToken(token, userEmail);

    if (!hash.isEmpty()) {
        // 保存成功，同时维护向后兼容的明文字段（设置为空表示使用安全存储）
        setNestedValue("user", "token", "");
        setNestedValue("user", "tokenSecure", true);
        setNestedValue("user", "tokenHash", hash);
    } else {
        setNestedValue("user", "token", token);
        setNestedValue("user", "tokenSecure", false);
        setNestedValue("user", "tokenHash", "");
    }
}

QString ConfigManager::getUserToken()
{

    // 检查是否使用安全存储
    bool isSecure = getNestedValue("user", "tokenSecure", false).toBool();

    if (isSecure) {
        // 使用安全Token管理器读取
        SecureTokenManager& secureManager = SecureTokenManager::instance();
        QString userEmail = getUserEmail();
        QString token = secureManager.loadAndDecryptToken(userEmail);

        return token;
    } else {
        // 向后兼容：从明文存储读取
        QString token = getNestedValue("user", "token", "").toString();

        // 如果存在明文Token，建议迁移到安全存储
        if (!token.isEmpty()) {
        }

        return token;
    }
}

void ConfigManager::setAuthToken(const QString& token)
{

    // 使用安全Token管理器存储
    SecureTokenManager& secureManager = SecureTokenManager::instance();
    QString userEmail = getUserEmail();
    QString storageKey = userEmail.isEmpty() ? "authToken" : QString("authToken_%1").arg(userEmail);
    QString hash = secureManager.encryptAndStoreToken(token, storageKey);

    if (!hash.isEmpty()) {
        // 保存成功，同时维护向后兼容的明文字段（设置为空表示使用安全存储）
        setNestedValue("user", "authToken", "");
        setNestedValue("user", "authTokenSecure", true);
        setNestedValue("user", "authTokenHash", hash);
    } else {
        setNestedValue("user", "authToken", token);
        setNestedValue("user", "authTokenSecure", false);
        setNestedValue("user", "authTokenHash", "");
    }
}

QString ConfigManager::getAuthToken()
{

    // 检查是否使用安全存储
    bool isSecure = getNestedValue("user", "authTokenSecure", false).toBool();

    if (isSecure) {
        // 使用安全Token管理器读取
        SecureTokenManager& secureManager = SecureTokenManager::instance();
        QString userEmail = getUserEmail();
        QString storageKey = userEmail.isEmpty() ? "authToken" : QString("authToken_%1").arg(userEmail);
        QString token = secureManager.loadAndDecryptToken(storageKey);

        return token;
    } else {
        // 向后兼容：从明文存储读取
        QString token = getNestedValue("user", "authToken", "").toString();

        // 如果存在明文Token，建议迁移到安全存储
        if (!token.isEmpty()) {
        }

        return token;
    }
}

void ConfigManager::setSubscriptionInfo(const QJsonObject& subscription)
{
    setNestedValue("user", "subscriptionInfo", subscription);
}

QJsonObject ConfigManager::getSubscriptionInfo()
{
    QJsonObject subscription = getNestedValue("user", "subscriptionInfo", QJsonObject()).toJsonObject();
    return subscription;
}

void ConfigManager::clearSubscriptionInfo()
{
    setNestedValue("user", "subscriptionInfo", QJsonObject());
}

// === 安全Token专用方法实现 ===
void ConfigManager::setSecureToken(const QString& token, const QString& email)
{

    SecureTokenManager& secureManager = SecureTokenManager::instance();
    QString hash = secureManager.encryptAndStoreToken(token, email);

    if (!hash.isEmpty()) {
        setNestedValue("user", "secureTokenHash", hash);
    } else {
    }
}

QString ConfigManager::getSecureToken(const QString& email)
{

    SecureTokenManager& secureManager = SecureTokenManager::instance();
    QString token = secureManager.loadAndDecryptToken(email);


    return token;
}

void ConfigManager::clearSecureToken(const QString& email)
{

    SecureTokenManager& secureManager = SecureTokenManager::instance();
    secureManager.clearStoredToken(email);
    setNestedValue("user", "secureTokenHash", "");

}

bool ConfigManager::isSecureTokenValid(const QString& email)
{

    SecureTokenManager& secureManager = SecureTokenManager::instance();
    bool isValid = !secureManager.loadAndDecryptToken(email).isEmpty();

    return isValid;
}

qint64 ConfigManager::getSecureTokenRemainingTime(const QString& email)
{

    SecureTokenManager& secureManager = SecureTokenManager::instance();
    qint64 remainingTime = secureManager.getTokenRemainingTime("");

    return remainingTime;
}
